/*******************************************************************************************
Copyright (C) 2013 Mestrelab Research S.L. All rights reserved.

This file is part of the MNova scripting toolkit.

Authorized users of MNova Software may use this file freely, but this file is provided AS IS
with NO WARRANTY OF ANY KIND, INCLUDING THE WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE.
*******************************************************************************************/

/*globals Application, MessageBox, settings, Dir, FileDialog, File, Peaks, Peak, TextStream, MnUi, qsTr*/
/*jslint plusplus: true, indent: 4*/

function importSparky2DPeakList(aFileName) {
	"use strict";
	var i, flist, peaks, slist, line, arrline, f1, f2, peak, allText, lines,
		dirSetKey = "importSparky2DPeakList/Dir",
		openDir = settings.value(dirSetKey, Dir.home()),
		spec = Application.nmr.activeSpectrum();

	if (spec.dimCount !== 2) {
		MessageBox.critical(qsTr("Select a destination 2D spectrum first."));
		return;
	}

	if (!aFileName) {
		aFileName = FileDialog.getOpenFileName(qsTr("Sparky 2D Peak List (*.list)"), "", openDir);
		if (!aFileName.length) {
			return;
		}

		settings.setValue(dirSetKey, File.absDirPath(aFileName));
	}

	flist = new File(aFileName);
	try {
		if (flist.open(File.ReadOnly)) {
			peaks = new Peaks();
			slist = new TextStream(flist);

			allText = slist.readAll();
			allText = allText.replace(/\r/g, "\n").replace(/\n\n/g, "\n");

			lines = allText.split("\n");

			for (i = 0; i < lines.length; i++) {
				line = lines[i];
				if (line) {
					line = line.replace(/^\s+|\s+$/g, "");
					arrline = line.split(/\s+/);
					if (!(arrline.length < 3 || isNaN(arrline[1]) || isNaN(arrline[2]))) {
						f1 = Number(arrline[1]);
						f2 = Number(arrline[2]);
						peak = new Peak(f1, f2, spec);
						peak.annotation = arrline[0];
						peaks.append(peak);
					}
				}
			}

			spec.setPeaks(peaks);
			spec.setProperty("peaks.show", true);
			spec.update();
			Application.mainWindow.activeDocument.update();
		}
	} finally {
		flist.close();
	}
}

if (this.MnUi && MnUi.scripts_nmr) {
	MnUi.scripts_nmr.scripts_nmr_ImportSparky2DPeakList = importSparky2DPeakList;
}
